<template>
  <div id="pinche">
    <md-scroll-view class="pin-scroll-view" ref="scrollView" :scrolling-x="false" @refreshing="$_onRefresh" :auto-reflow="true">
      <md-scroll-view-refresh
        slot="refresh"
        slot-scope="{ scrollTop, isRefreshActive, isRefreshing }"
        :scroll-top="scrollTop"
        :is-refreshing="isRefreshing"
        :is-refresh-active="isRefreshActive"
      ></md-scroll-view-refresh>
      <div>
        <div class="field_box">
          <md-field>
            <md-input-item
              :value="startInfoString"
              class="no-right-padding"
              ref="startLocation"
              :placeholder="getRoute?getRoute.start_auto_name +'  从哪出发':''"
              readonly
              @click.native="selectStart"
            >
              <md-icon class="place_icon" name="shangchedian" slot="left"></md-icon>
              <div v-if="false" slot="right" class="out_tag">
                不在服务范围内
                <md-icon class="tk_close" name="tk_close"></md-icon>
              </div>
            </md-input-item>
            <md-input-item
              :value="endInfoString"
              class="no-right-padding"
              ref="endLocation"
              :placeholder="getRoute?getRoute.end_auto_name + '  您要去哪':''"
              readonly
              @click.native="selectEnd"
            >
              <md-icon class="place_icon" name="xiachedian" slot="left"></md-icon>
              <div v-if="false" slot="right" class="out_tag">
                不在服务范围内
                <md-icon class="tk_close" name="tk_close"></md-icon>
              </div>
            </md-input-item>
            <md-input-item :value="getPinStartTimeString" v-if="positionSelected" ref="startTime" placeholder="出发时间" readonly @click.native="selectStartTime">
              <md-icon class="place_icon" name="time" slot="left"></md-icon>
            </md-input-item>
            <md-field-item :customized="true">
              <md-input-item
                v-if="positionSelected"
                class="inline_field"
                ref="numSelector"
                placeholder="乘车人数"
                readonly
                slot="left"
                :value="pinNumPassenger!=0?pinNumPassenger+'人':''"
                @click.native="selectPassenegerNum"
              >
                <md-icon class="place_icon" name="pc_pcrs" slot="left"></md-icon>
              </md-input-item>
              <md-input-item
                v-if="positionSelected"
                class="inline_field"
                ref="remarks"
                placeholder="出行备注"
                readonly
                slot="right"
                :value="getPinSelectedRemarks.length>0?'已添加':''"
                @click.native="selectCommet"
              >
                <md-icon class="place_icon" name="chuxingbeizhu" slot="left"></md-icon>
              </md-input-item>
            </md-field-item>
            <div class="cost-info" v-show="getPinCostInfo">
              <div class="row centered">
                <div class="price">
                  <span class="symbol">￥</span>
                  {{getPinCostInfo?getPinCostInfo.prefePrice:''}}
                </div>
                <md-icon name="wdqb-more" @click="gotoCostDetail"></md-icon>
              </div>
              <div class="desc" v-if="getPinCostInfo&&getPinCostInfo.cheapFlag=='1'">
                原价{{getPinCostInfo.price}}元，券已抵
                <span style="color:#FF6917">{{getPinCostInfo.cheapPrice}}</span>元
              </div>
            </div>
            <md-button class="submit-btn" v-if="positionSelected" @click="submitOrder" :disabled="!getPinCostInfo">提交订单</md-button>
          </md-field>
        </div>
        <div class="adv" v-if="getPinAdv?getPinAdv.url!='':false">
          <a :href="getPinAdv?getPinAdv.url:''" target="_blank">
            <img class="img" :src="getPinAdv?getPinAdv.img:''" />
          </a>
        </div>
        <div class="waiting_list">
          <div class="title_field" @click="selectWaitingTime">
            <div class="hint">待出发行程({{getWaitingRoute?getWaitingRoute.length:''}})</div>
            <div class="time_string">
              {{currentWaitingDate.text}}
              <md-icon name="right_arrow"></md-icon>
            </div>
          </div>
          <div class="line"></div>
          <div v-if="getWaitingRoute&&getWaitingRoute.length==0">
            <div style="padding:120px;" class="column centered">
              <img style="width:220px;height:149px;margin-bottom:20px;" :src="require('@/assets/imgs/xc_kb.png')" />
              <div style="font-size:24px;line-height:34px;color:#666666">暂无新的待出发行程哦～</div>
            </div>
          </div>
          <waiting-route-item v-for="(item,index) in getWaitingRoute" :key="index" :info="item"></waiting-route-item>
        </div>
      </div>
    </md-scroll-view>
  </div>
</template>

<script>
import '@/assets/svgs/shangchedian.svg';
import '@/assets/svgs/xiachedian.svg';
import '@/assets/svgs/time.svg';
import '@/assets/svgs/pc_pcrs.svg';
import '@/assets/svgs/chuxingbeizhu.svg';
import '@/assets/svgs/right_arrow.svg';
import '@/assets/svgs/tk_close.svg';
import '@/assets/svgs/wdqb-more.svg';
import { mapGetters } from 'vuex';
import { Field, FieldItem, Icon, InputItem, Button, Tag, ScrollView, ScrollViewRefresh, Dialog } from 'mand-mobile';
import Popup from './popup';
import Map from '@/components/map';
import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
import { COST_ESTIMAT_CARPOOL, ORDER_SUBMIT, GET_WAITING_ROUTE_LIST, GET_ORDER_TIME } from '@/store/actions.types';
import WaitingRouteListItem from './waitingroute/WaitingRouteListItem';
import Utils from '@/common/pakjUtils';
var moment = require('moment');
moment.locale('zh-cn');
export default {
  name: 'pinche',
  components: {
    [Field.name]: Field,
    [FieldItem.name]: FieldItem,
    [Icon.name]: Icon,
    [InputItem.name]: InputItem,
    [Button.name]: Button,
    [WaitingRouteListItem.name]: WaitingRouteListItem,
    [ScrollView.name]: ScrollView,
    [ScrollViewRefresh.name]: ScrollViewRefresh,
    Tag
  },
  data() {
    return {
      positionSelected: false,
      hasCostInfo: false,
      currentWaitingDate: {
        // 待出发行程时间
        text: '',
        value: null
      }
    };
  },
  created() {
    let now = moment();
    this.currentWaitingDate.text = now.format('MMMDo') + '今天';
    this.currentWaitingDate.value = now;
    if (this.getPinStartInfo && this.getPinEndInfo) {
      this.positionSelected = true;
    } else {
      this.positionSelected = false;
    }
    if (this.getPinCostInfo) {
      this.hasCostInfo = true;
    } else {
      this.hasCostInfo = false;
    }
  },
  methods: {
    selectStart() {
      Map.createMap(true, '1', this.getRoute.pin_opt_type_start)
        .then(() => {
          if (this.getPinEndInfo && !this.promised) {
            this.startPromise();
          } else {
            this.getCostInfo();
          }
        })
        .catch(reason => {
          if (reason.message === 'bao') {
            this.$emit(reason.message);
          }
        });
    },
    selectEnd() {
      Map.createMap(false, '1', this.getRoute.pin_opt_type_end)
        .then(() => {
          if (this.getPinStartInfo && !this.promised) {
            this.startPromise();
          } else {
            this.getCostInfo();
          }
        })
        .catch(reason => {
          if (reason.message === 'bao') {
            this.$emit(reason.message);
          }
        });
    },
    selectStartTime() {
      this.$store.dispatch(GET_ORDER_TIME, '拼车').then(() => {
        Popup.createTimeSelector2().then(() => {
          this.getCostInfo();
        });
      });
    },
    selectPassenegerNum() {
      Popup.createNumberSelector().then(() => {
        this.getCostInfo();
      });
    },
    selectCommet() {
      Popup.createRemarkSelector('1').then(() => {
        this.getCostInfo();
      });
    },
    startPromise() {
      this.$store.dispatch(GET_ORDER_TIME, '拼车').then(() => {
        Popup.createTimeSelector2()
          .then(() => {
            Popup.createNumberSelector()
              .then(() => {
                Popup.createRemarkSelector('1')
                  .then(() => {
                    this.getCostInfo();
                  })
                  .catch(reason => {
                    this.getCostInfo();
                  });
              })
              .catch(reason => {
                this.getCostInfo();
              });
          })
          .catch(reason => {
            this.getCostInfo();
          });
      });
    },
    selectWaitingTime() {
      Popup.createWaitingDateSelector().then(date => {
        this.currentWaitingDate = date;
        this.$store.dispatch(GET_WAITING_ROUTE_LIST, date.value.format('YYYY-MM-DD'));
      });
    },
    $_onRefresh() {
      console.log(this.currentWaitingDate);
      this.$store.dispatch(GET_WAITING_ROUTE_LIST, this.currentWaitingDate.value.format('YYYY-MM-DD')).then(() => {
        this.$refs.scrollView.finishRefresh();
      });
    },
    getCostInfo() {
      if (!this.canGetCostInfo) {
        return;
      }
      let params = {
        route_id: this.getRoute.route_id,
        origin_coord: encryptByDESModeEBC(this.getPinStartInfo.coordinate[0] + ',' + this.getPinStartInfo.coordinate[1]),
        dest_coord: encryptByDESModeEBC(this.getPinEndInfo.coordinate[0] + ',' + this.getPinEndInfo.coordinate[1]),
        travel_time: this.getPinConfirmStartTime.time.valueOf().toString(),
        travel_end_time: this.getPinConfirmStartTime.endTime.valueOf().toString(),
        order_num: this.pinNumPassenger.toString()
      };
      if (this.getPinStartInfo.routeStationId) {
        params.start_site = this.getPinStartInfo.routeStationId;
      }
      if (this.getPinEndInfo.routeStationId) {
        params.end_site = this.getPinEndInfo.routeStationId;
      }
      this.$store.dispatch(COST_ESTIMAT_CARPOOL, params);
    },
    submitOrder() {
      let params = {
        route_id: this.getRoute.route_id,
        origin: this.getPinStartInfo.stationName,
        origin_label_detailed: this.getPinStartInfo.position,
        origin_coord: encryptByDESModeEBC(this.getPinStartInfo.coordinate[0] + ',' + this.getPinStartInfo.coordinate[1]),
        destination: this.getPinEndInfo.stationName,
        dest_label_detailed: this.getPinEndInfo.position,
        dest_coord: encryptByDESModeEBC(this.getPinEndInfo.coordinate[0] + ',' + this.getPinEndInfo.coordinate[1]),
        travel_time: this.getPinConfirmStartTime.time.valueOf().toString(),
        travel_end_time: this.getPinConfirmStartTime.endTime.valueOf().toString(),
        order_num: this.pinNumPassenger.toString(),
        remarks: this.getPinSelectedRemarksString,
        systemType: Utils.getCurrentEnv(),
        platformId: this.getPlatformId,
        order_type: '拼车'
      };
      if (this.getPinStartInfo.routeStationId) {
        params.start_site = this.getPinStartInfo.routeStationId;
      }
      if (this.getPinEndInfo.routeStationId) {
        params.end_site = this.getPinEndInfo.routeStationId;
      }
      if (this.getSelectedContact) {
        params.passenger_name = this.getSelectedContact.name;
        params.passenger_mobile = encryptByDESModeEBC(this.getSelectedContact.phone);
      }
      this.$store
        .dispatch(ORDER_SUBMIT, params)
        .then(() => {
          this.$router.push({
            name: 'OrderPayment',
            query: {
              orderno: this.getOrderInfoData.order_no
            }
          });
          this.$store.commit('resetRoute');
        })
        .catch(reason => {
          Dialog.alert({
            title: '温馨提示',
            content: reason.message,
            confirmText: '确定'
          });
        });
    },
    gotoCostDetail() {
      // this.$router.push({
      //     name: 'beforechargesDetails',
      //     query: {
      //         orderno: this.getPinCostInfo.cost_id
      //     }
      // })
      Popup.createChargeDetail(this.getPinCostInfo.cost_id);
    },
    update() {
      console.log('拼车UPDATE');
      if (this.getPinStartInfo && this.getPinEndInfo) {
        this.positionSelected = true;
        if (this.getPinConfirmStartTime && this.pinNumPassenger > 0) {
          this.getCostInfo();
        } else {
          this.hasCostInfo = false;
          this.$store.commit('setPinCostInfo', null);
        }
      } else {
        this.hasCostInfo = false;
        this.positionSelected = false;
        this.$store.commit('setPinCostInfo', null);
      }
    }
  },
  updated() {
    if (this.getPinStartInfo && this.getPinEndInfo) {
      this.positionSelected = true;
    } else {
      this.positionSelected = false;
    }
  },
  computed: {
    startInfoString() {
      let str = '';
      if (this.getPinStartInfo) {
        str = this.getRoute.start_auto_name + '  ' + this.getPinStartInfo.stationName;
      }
      return str;
    },
    endInfoString() {
      let str = '';
      if (this.getPinEndInfo) {
        str = this.getRoute.end_auto_name + '  ' + this.getPinEndInfo.stationName;
      }
      return str;
    },
    canGetCostInfo() {
      return this.getPinStartInfo && this.getPinEndInfo && this.getPinConfirmStartTime && this.pinNumPassenger;
    },
    ...mapGetters([
      'getConfirmdRoute',
      'getRoute',
      'getPlatformId',
      'getWaitingRoute',
      'getPinStartInfo',
      'getPinEndInfo',
      'getPinConfirmStartTime',
      'getPinStartTimeString',
      'pinNumPassenger',
      'getPinSelectedRemarks',
      'getPinCostInfo',
      'getPinSelectedRemarksString',
      'getOrderInfoData',
      'getPinAdv',
      'getSelectedContact'
    ])
  }
};
</script>

<style lang="stylus">
#pinche {
  padding: 20px;
  height: calc(100vh - 210px);

  .pin-scroll-view {
    background-color: transparent;
  }

  .field_box {
    background-color: #fff;
    box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.08);
    border-radius: 10px;
    padding: 5px;

    .no-right-padding {
      padding-right: 20px;
    }

    .field_item {
      height: 88px;
      font-size: 28px;
    }

    .place_icon {
      width: 20px;
      height: 20px;
    }

    .out_tag {
      width: 236px;
      height: 60px;
      background: rgba(0, 0, 0, 0.6);
      border-radius: 6px;
      color: #fff;
      font-size: 26px;
      display: flex;
      justify-content: center;
      align-items: center;
      line-height: 36px;

      .tk_close {
        width: 16px;
        height: 16px;
        color: #333;
        margin-left: 8px;
      }
    }

    .inline_field {
      padding: 0px;
    }

    .md-field-item {
      .md-field-item-inner {
        padding-top: 0px;
        padding-bottom: 0px;
      }
    }

    .md-input-item-right {
      width: 250px;
      justify-content: flex-end;
    }

    .cost-info {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      padding: 20px;

      .price {
        font-size: 52px;
        text-align: center;
        margin-right: 10px;

        .symbol {
          font-size: 36px;
        }
      }

      .desc {
        width: 283px;
        height: 34px;
        font-size: 24px;
        text-align: center;
        width: 100%;
        color: color-text-caption;
      }
    }

    .submit-btn {
      margin: 20px;
      width: auto !important;
    }
  }

  .adv {
    margin-top: 22px;

    .img {
      width: 100%;
      height: 150px;
      object-fit: cover;
      border-radius: 10px;
    }
  }

  .waiting_list {
    background-color: #fff;
    box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.08);
    border-radius: 10px;
    padding: 20px 30px;
    margin-top: 20px;

    .title_field {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .time_string {
      color: color-text-caption;
      display: flex;
      align-items: center;
      padding: 20px 0;

      .md-icon {
        width: 12px;
        height: 20px;
        margin-left: 10px;
      }
    }

    .line {
      border-bottom: 1px solid #E0E0E0;
    }
  }
}
</style>
